package com.kaifamiao.resp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@WebServlet( "/show/time" )
public class ShowTimeServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置向 "响应对象" 中输出字符数据时使用的编码
        response.setCharacterEncoding( "UTF-8" );
        // 设置响应头
        response.setHeader( "content-type" , "text/html;charset=UTF-8" );
        // 获得可以向 "响应对象" 中输出字符数据的 字符输出流(打印流)
        PrintWriter out = response.getWriter();

        LocalDateTime datetime = LocalDateTime.now();
        String pattern = "G yyyy年MM月dd日 E HH点mm分ss秒SSS毫秒" ;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern( pattern );
        String time = formatter.format( datetime );

        // 通过字符输出流(打印流) 向 "响应对象" 中输出字符数据
        out.println( "<div style=\"color:blue;text-align:center;\">" );
        out.println( time );
        out.println( "</div>" );

        // 当 service 方法执行完毕，容器会将 response 转换成 HTTP响应 并将其发送给客户端
    }

}
